import {useState, useEffect, useRef} from 'react';
import {Form, Input, Button, Typography, message, Row, Col, Card} from 'antd';
import {UserOutlined, LockOutlined, MailOutlined} from '@ant-design/icons';
import {useNavigate} from 'react-router-dom';
import {login, sendVerificationCode, verifyEmailCode} from '../api/loginApi';
import '../styles/LoginPage.css'; // Import custom CSS

const {Title} = Typography;

const LoginPage = () => {
    const [loading, setLoading] = useState(false);
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [verificationCode, setVerificationCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const [loginMethod, setLoginMethod] = useState('password');
    const [messageApi, contextHolder] = message.useMessage();

    const rippleContainerRef = useRef(null);

    const navigate = useNavigate();

    const onFinish = async () => {
        setLoading(true);
        console.log('loginMethod', loginMethod)
        if (loginMethod === 'password') {
            const loginForm = {
                email: email,
                password: password,
            };
            login(loginForm).then(res => {
                handleLoginResponse(res);
            }).finally(() => {
                setLoading(false)
            })
        } else {
            const loginForm = {
                email: email,
                verifyCode: verificationCode,
            };
            const res: any = await verifyEmailCode(loginForm);
            handleLoginResponse(res);
        }
        setLoading(false);
    };

    const handleLoginResponse = (res: any) => {
        if (res['code'] === '00000') {
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("UserRole", res.data.Role);
            localStorage.setItem("UserID", res.data.UserID);
            navigate("/home");
        } else {
            messageApi.warning('Login failed: ' + res['message']);
        }
    };

    const handleSendCode = async () => {
        if (!email) {
            messageApi.warning('Please input your email first!');
            return;
        }
        const param: object = {
            type: 1,
            email: email,
        }
        const res: any = await sendVerificationCode(param);
        console.log('res', res)
        if (res?.code === 200) {
            messageApi.success('Verification code sent successfully!');
            setCountdown(60);
        } else {
            messageApi.warning('Failed to send verification code: ' + res['message']);
        }
    };

    useEffect(() => {
        let timer: NodeJS.Timeout;
        if (countdown > 0) {
            timer = setInterval(() => {
                setCountdown((prevCountdown) => prevCountdown - 1);
            }, 1000);
        }
        return () => clearInterval(timer);
    }, [countdown]);

    const handleToggleLoginMethod = () => {
        setLoginMethod((prevMethod) => (prevMethod === 'password' ? 'code' : 'password'));
    };


    const createRipple = (event: any) => {
        const rippleContainer: any = rippleContainerRef.current;

        // 确保 rippleContainer 存在
        if (!rippleContainer) return;

        // 检查点击的元素是否是 login-form-container 或者它的子元素
        const targetElement = event.target as HTMLElement;
        if (targetElement.closest('.login-form-container')) {
            return; // 如果是 login-form-container 区域，则不产生水波纹
        }

        // 获取水波纹起始位置
        const rect = rippleContainer.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        // 创建水波纹效果的 span 元素
        const ripple = document.createElement("span");
        ripple.className = "ripple-effect";
        ripple.style.left = `${x}px`;
        ripple.style.top = `${y}px`;

        // 将水波纹元素添加到容器中
        rippleContainer.appendChild(ripple);

        // 在动画完成后移除水波纹元素
        ripple.addEventListener('animationend', () => {
            ripple.remove();
        });
    };


    return (
        <>
            {contextHolder}
            <div ref={rippleContainerRef} className="login-container" onMouseMove={createRipple}>
                <div className="login-header">
                    <Title level={2} style={{color: 'white', fontSize: '48px'}}>Task Platform</Title>
                </div>
                <div className="login-form-container">
                    <div className="login-toggle">
                        <Button type="link" onClick={handleToggleLoginMethod}>
                            {loginMethod === 'password' ? 'Use Verification Code Login' : 'Use Password Login'}
                        </Button>
                    </div>
                    <Card className={`password-login ${loginMethod === 'password' ? 'active' : ''}`}>
                        <Form
                            name="loginForm"
                            initialValues={{remember: true}}
                            onFinish={onFinish}
                        >
                            <Form.Item
                                name="email"
                                rules={[{required: true, message: 'Please input your email!'}]}
                            >
                                <Input
                                    style={{height: '50px', borderRadius: '10px'}}
                                    onChange={e => setEmail(e.target.value)}
                                    prefix={<UserOutlined/>}
                                    placeholder="Email"
                                />
                            </Form.Item>
                            <Form.Item
                                name="password"
                                rules={[{required: true, message: 'Please input your password!'}]}
                            >
                                <Input.Password
                                    style={{height: '50px', borderRadius: '10px'}}
                                    onChange={e => setPassword(e.target.value)}
                                    prefix={<LockOutlined/>}
                                    placeholder="Password"
                                />
                            </Form.Item>
                            <Form.Item>
                                <Button style={{height: '50px', borderRadius: '50px'}} type="primary" htmlType="submit"
                                        loading={loading} block>
                                    Log in
                                </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                    <Card className={`password-email ${loginMethod === 'code' ? 'active' : ''}`}>
                        <Form
                            name="loginForm"
                            initialValues={{remember: true}}
                            onFinish={onFinish}
                        >
                            <Row gutter={8}>
                                <Col span={16}>
                                    <Form.Item
                                        name="email"
                                        rules={[{required: true, message: 'Please input your email!'}]}
                                    >
                                        <Input
                                            style={{height: '50px', borderRadius: '10px', width: '330px'}}
                                            onChange={e => setEmail(e.target.value)}
                                            prefix={<UserOutlined/>}
                                            placeholder="Email"
                                        />
                                    </Form.Item>

                                </Col>
                            </Row>
                            <Row gutter={8}>
                                <Col span={16}>
                                    <Form.Item
                                        name="verificationCode"
                                        rules={[{required: true, message: 'Please input the verification code!'}]}
                                    >
                                        <Input
                                            style={{
                                                height: '50px',
                                                borderTopLeftRadius: '10px',
                                                borderBottomLeftRadius: '10px',
                                                borderTopRightRadius: '0px',
                                                borderBottomRightRadius: '0px'
                                            }}
                                            onChange={e => setVerificationCode(e.target.value)}
                                            prefix={<MailOutlined/>}
                                            placeholder="Verification Code"
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Button
                                        style={{
                                            height: '50px',
                                            borderRadius: '10px',
                                            color: countdown > 0 ? 'black' : 'white',
                                            borderTopLeftRadius: '0px',
                                            borderBottomLeftRadius: '0px',
                                            marginLeft: '-10px',
                                            zIndex:999
                                        }}
                                        onClick={handleSendCode}
                                        type="primary"
                                        disabled={countdown > 0}
                                        block
                                    >
                                        {countdown > 0 ? `Resend in ${countdown}s` : 'Send Code'}
                                    </Button>
                                </Col>
                            </Row>

                            <Form.Item>
                                <Button style={{height: '50px', borderRadius: '50px'}} type="primary" htmlType="submit"
                                        size={'large'}
                                        loading={loading} block>
                                    Log in
                                </Button>
                            </Form.Item>

                        </Form>
                    </Card>
                    <div style={{textAlign: 'center'}}>
                        <Button onClick={() => navigate('/register')} type="link">Register</Button>
                    </div>
                </div>
            </div>
        </>
    );
};

export default LoginPage;
